﻿using AutoMapper;
using MediatR;
using MyRabbit.Application.Command;
using MyRabbit.Application.Dtos;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRabbit.Application.CommandHandler
{
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, APIResult<UserDTO>>
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IRepository<User> userRep;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRep"></param>
        public LoginQueryCommandHandler(IRepository<User> userRep,IMapper mapper)
        {
            this.userRep = userRep;
            this.mapper = mapper;
        }


        public async Task<APIResult<UserDTO>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDTO> result = new APIResult<UserDTO>();
            result.Code=Codes.登录成功;
            result.Message = Codes.登录成功.ToString();
            var list = await userRep.GetByConditionAsync(w=>w.UserName==request.UserName);
            try
            {
                if (list == null)
                {
                    throw new Exception("用户名不存在");
                }
                if (list.UserPass != request.UserPass)
                {
                    throw new Exception("用户名与密码不匹配");
                }
                result.Data=mapper.Map<UserDTO>(list);
                
                
            }
            catch (Exception exp)
            {

                result.Code = Codes.登录失败;
                result.Message=Codes.登录失败.ToString()+exp.Message;
            }

            return await Task.FromResult(result); 
        }
    }
}
